<?php
class TbfSerialize {
    /**
     * 使用map填充 一个对象里面的public字段
     * @param $obj
     * @param $data
     * @return $obj
     */
    public static function objPublicFieldLoadFromArray($obj,$data){
        if (!is_object($obj)) {
            throw new \Exception('input is not object');
        }
        $meta_class = TbfReflect::getReflectionClass(get_class($obj));
        foreach ($meta_class->getProperties() as $meta_property) {
            if (!$meta_property->isPublic()){
                continue;
            }
            $name = $meta_property->getName();
            if (array_key_exists($name,$data)) {
                $meta_property->setValue($obj,$data[$name]);
            }
        }
        return $obj;
    }
    /**
     * 把一个对象里面的public字段转成数组
     * @return array
     */
    public static function objPublicFieldToArray($obj){
        if (is_array($obj)) {
            return $obj;
        }
        $output = array();
        $meta_class = TbfReflect::getReflectionClass(get_class($obj));
        //getter自动处理
        foreach ($meta_class->getProperties() as $meta_property) {
            if (!$meta_property->isPublic()){
                continue;
            }
            $name = $meta_property->getName();
            $value = $meta_property->getValue($obj);
            $output[$name] = $value;
        }
        return $output;
    }

    public static function objPublicFieldNullToStringEmpty($obj){
        $meta_class = TbfReflect::getReflectionClass(get_class($obj));
        //getter自动处理
        foreach ($meta_class->getProperties() as $meta_property) {
            if (!$meta_property->isPublic()){
                continue;
            }
            if ($meta_property->getValue($obj)===null){
                $meta_property->setValue($obj,'');
            }
        }
    }
} 